package com.xy.iot.serial.port;

import com.xy.iot.serial.port.listener.MySerialPortEventListener;
import com.xy.iot.serial.port.utils.SerialPortUtil;
import gnu.io.SerialPort;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.List;

/**
 * @description: gnu 组建串口相关操作
 * 案例说明网址：<a href="https://blog.csdn.net/weixin_43943548/article/details/109843533">使用java进行串口开发测试，超详细（一篇就够了）！</a>
 */
@Slf4j
public class GnuStartMain {
    private static SerialPort serialPort;
    /**
     * 开启串口
     * @param portName 串口名称
     * @param timeout 超时时间
     * @param baudRate 波特率
     * @param dataBits 数据位
     * @param stopBits 停止位
     * @param parity 校验位（奇偶位）
     * @return
     */
    public boolean start(String portName, int timeout, int baudRate, int dataBits, int stopBits, int parity) {
        boolean response = false;
        try {

            serialPort = SerialPortUtil.openPort(portName, timeout, baudRate,dataBits, stopBits, parity);
            //给对应的serialPort添加监听器
            SerialPortUtil.addListener(serialPort,new MySerialPortEventListener(serialPort));
            response = true;
            log.info("启动串口成功：{}",portName);
        }catch (Exception e){
            log.error("启动串口发生错误",e);
        }
       return response;
    }

    /**
     * 关闭串口
     * @return
     */
    public boolean stop(){
        boolean response = false;
        try {
            SerialPortUtil.removeListener(serialPort,new MySerialPortEventListener(serialPort));
            SerialPortUtil.closePort(serialPort);
            response = true;
            log.info("关闭串口成功");
        }catch (Exception e){
            log.error("关闭串口发生错误",e);
        }
        return response;
    }

    /**
     * 得到所以串口
     * @return
     */
    public List<String> getAllPort(){
        return SerialPortUtil.findPort();
    }
    /**
     * 发送数据
     * @param bytes 发送的数据
     */
    public void send(byte[] bytes){
        SerialPortUtil.sendToPort(serialPort,bytes);
    }

    /**
     * 测试串口
     * @param args
     */
    public static void main(String[] args) {
        GnuStartMain gnuStartMain = new GnuStartMain();
        try {
            List<String> allPort = gnuStartMain.getAllPort();
            log.info("串口列表：{}",allPort);
            String portName = "COM2";
            gnuStartMain.start(portName, 6000,9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            //监听退出
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    synchronized (GnuStartMain.class) {
                        gnuStartMain.stop();
                    }
                }
            });
        }catch (Exception exception ){
            log.error("串口发生错误",exception);
        }
    }
}
